<template>
  <div class="main-con flex1 hbox scanweight">
    <audio ref="audio" style></audio>
    <el-tabs class="vbox flex1" v-model="activeName" type="border-card" @tab-click="tabClick">
      <el-tab-pane label="入库操作" name="into">
        <div class="hbox flex1">
          <div class="vbox prd-table" style="border-right:10px solid #eee">
            <div class="search-con">
              <el-form :model="searchParam" :inline="true">
                <el-form-item prop="prdName">
                  <el-input
                    v-model.trim="searchParam.prdName"
                    @keyup.enter.native="search"
                    placeholder="输入产品名称查询"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button icon="el-icon-search" type="primary" @click="search">查询</el-button>
                </el-form-item>
              </el-form>
            </div>
            <base-table
              ref="productTable"
              url="product/getPage"
              code="htk"
              :param="searchParam"
              :cls="columns"
              @current-change="handleCurrentChange"
            ></base-table>
          </div>
          <div class="vbox flex1" style="border-right:10px solid #e5e5e5">
            <div class="search-con">
              <el-form :model="order" label-width="95px">
                <el-col :span="8">
                  <el-form-item label="客户编码">
                    <el-select
                      style="width:100%"
                      clearable
                      filterable
                      v-model="order.consumerCode"
                      placeholder="请选择客户"
                      :filter-method="filterMethod"
                      @change="changeConsumer"
                    >
                      <el-option
                        v-for="item in consumerOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.code"
                      >
                        <span style="float: left">{{ item.name }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="目的地">
                    <base-select
                      type="custom"
                      code="htk-admin"
                      v-model.trim="order.destination"
                      url="country/selectCountries"
                      placeholder="请选择路向（目的地）"
                      @changeObj="changeDestination"
                    ></base-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8"></el-col>
                <!-- <el-form-item :span="8">
                  <el-form-item label="服务商编码">
                    <el-select
                      style="width:100%"
                      clearable
                      filterable
                      v-model="order.transportation"
                      placeholder="请选择服务商编码"
                      @change="changePrice"
                    >
                      <el-option
                        v-for="item in prices"
                        :key="item.id"
                        :label="'海淘客-'+order.prdName+'-'+item.destination"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>-->
                <el-col :span="8">
                  <el-form-item label="重量">
                    <el-input-number
                      ref="roughWeight"
                      style="width:100%"
                      v-model="order.roughWeight"
                      :min="0"
                      :precision="3"
                      placeholder="扫描称重"
                      @keyup.enter.native="processWeight"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="8"></el-col>
                <el-col :span="8">
                  <el-form-item label="转运单号">
                    <el-input
                      ref="afterCode"
                      style="width:100%"
                      v-model.trim="order.afterCode"
                      @keyup.enter.native="processAfterCode"
                      placeholder="转运单号"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="长度(cm)">
                    <el-input-number
                      style="width:100%"
                      v-model="order.longs"
                      :precision="3"
                      placeholder="请输入长度"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="宽度(cm)">
                    <el-input-number
                      style="width:100%"
                      v-model="order.width"
                      :precision="3"
                      placeholder="请输入宽度"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="高度(cm)">
                    <el-input-number
                      style="width:100%"
                      v-model="order.height"
                      :precision="3"
                      placeholder="请输入长度"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item>
                    <el-button type="primary" @click="submitOrder">手动保存</el-button>
                  </el-form-item>
                </el-col>
              </el-form>
            </div>
            <div class="vbox flex1">
              <el-table :data="tableData" style="width: 100%" class="flex1">
                <el-table-column prop="afterCode" label="运单号" width="150px"></el-table-column>
                <el-table-column prop="consumerName" label="客户名称"></el-table-column>
                <el-table-column prop="destinationName" label="目的地"></el-table-column>
                <el-table-column prop="weight" label="预报重量"></el-table-column>
                <el-table-column prop="roughWeight" label="实际重量"></el-table-column>
                <el-table-column prop="netWeight" label="重量偏差"></el-table-column>
                <el-table-column prop="transportationName" label="服务商"></el-table-column>
                <el-table-column fixed="right" label="操作" width="100">
                  <template slot-scope="scope">
                    <el-button @click="rollback(scope.row)" type="text" size="small">回撤</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="出库操作" name="out">
        <div class="vbox flex1">
          <div style="padding:10px;width:1080px;">
            <el-form label-width="95px">
              <el-row :gutter="15">
                <el-col :span="6">
                  <el-form-item label="转运单号">
                    <el-input
                      ref="outAfterCode"
                      style="width:100%"
                      v-model.trim="outAfterCode"
                      @keyup.enter.native="processOutAfterCode"
                      placeholder="转运单号"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="类型">
                    <el-select v-model="outType">
                      <el-option value label="默认"></el-option>
                      <el-option value="1" label="复称"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="重量">
                    <el-input-number
                      ref="outWeight"
                      style="width:100%"
                      v-model="outWeight"
                      :min="0"
                      :disabled="outType!=1"
                      :precision="3"
                      @keyup.enter.native="processOutWeight"
                      placeholder="扫描称重"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item>
                    <el-button type="primary" @click="clearData">清空</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="vbox flex1">
            <el-table :data="outTableData" style="width: 100%" class="flex1">
              <el-table-column prop="afterCode" label="运单号" width="150px"></el-table-column>
              <el-table-column prop="consumerCode" label="客户编号"></el-table-column>
              <el-table-column prop="destination" label="目的地"></el-table-column>
              <el-table-column prop="weight" label="预报重量"></el-table-column>
              <el-table-column prop="roughWeight" label="实际重量"></el-table-column>
              <el-table-column prop="netWeight" label="重量偏差"></el-table-column>
              <el-table-column prop="transportationName" label="服务商" width="150px"></el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeName: "into",
      searchParam: {},
      tableData: [],
      columns: [
        { prop: "prdCode", label: "产品编码", width: 100 },
        { prop: "prdName", label: "产品名称" }
      ],
      prds: [],
      parentConsumers: [],
      consumerOptions: [],
      order: {
        id: "",
        prdCode: "",
        commodityCode: "",
        consumerCode: "",
        destination: "",
        afterCode: "",
        roughWeight: 0,
        weight: 0,
        transportation: "",
        state: 20
      },
      prices: [],
      oldOrder: {},
      consumerName: "",
      transportationName: "",
      destinationName: "",
      outAfterCode: "",
      outWeight: "",
      outTableData: [],
      outOrder: {},
      outType: "",
      newOrder: {}
    };
  },
  watch: {
    "order.destination"(v) {
      if (!v) {
        this.prices = [];
        this.order.transportation = "";
      } else {
        this.getPriceList();
      }
    },
    activeName(v) {
      let me = this;
      if (v == "into") {
        setTimeout(() => {
          me.$refs["roughWeight"].focus();
        }, 100);
      } else if (v == "out") {
        setTimeout(() => {
          me.$refs["outAfterCode"].focus();
        }, 100);
      }
    },
    outType(v) {
      let me = this;
      if (v == 0 || v == "") {
        me.outWeight = 0;
      }
      setTimeout(() => {
        me.$refs["outAfterCode"].focus();
      }, 100);
    }
  },
  activated() {
    this.getParentConsumers();
    this.getPrdList();
    this.$refs["roughWeight"].focus();
  },
  methods: {
    tabClick(tab) {
      // console.log(tab.name);
      // if (tab.name == "into") {
      //   this.$refs["roughWeight"].focus();
      // } else if (tab.name == "out") {
      //   this.$refs["outAfterCode"].focus();
      // }
    },
    search() {
      this.$refs["productTable"].initLoad();
    },
    changePrice(v) {
      let valObj = this.prices.find(item => {
        return v == item.id;
      });
      if (valObj) {
        this.transportationName =
          "海淘客-" + this.order.prdName + "-" + valObj.destination;
      }
    },
    changeConsumer(v) {
      let valObj = this.parentConsumers.find(item => {
        return v == item.code;
      });
      if (valObj) {
        this.consumerName = valObj.name;
      }
    },
    changeDestination(obj) {
      if (obj) {
        this.audioTxt(obj.zhName);
        this.destinationName = obj.zhName;
      } else {
        this.destinationName = "";
      }
    },
    audioTxt(text) {
      this.$refs.audio.src =
        "http://tsn.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=5&per=1&text=" +
        text;
      this.$refs.audio.play();
    },
    clearData() {
      this.outTableData = [];
    },
    processWeight() {
      let weight = this.order.roughWeight + "";
      console.log(weight);
      if (weight.indexOf(".") == -1) {
        if (weight.length <= 6) {
          this.$refs["afterCode"].focus();
          this.audioTxt(this.order.roughWeight);
        } else {
          let tempData = this.order.roughWeight;
          this.order.afterCode = tempData;
          this.order.roughWeight = "";
          this.$refs["roughWeight"].focus();
        }
      } else {
        this.$refs["afterCode"].focus();
        this.audioTxt(this.order.roughWeight);
      }
      this.getOrderByAfterCode();
    },
    processAfterCode() {
      if (this.order.afterCode.indexOf(".") > -1) {
        let tempData = this.order.afterCode;
        this.order.roughWeight = tempData;
        this.order.afterCode = "";
        this.$refs["afterCode"].focus();
        this.audioTxt(this.order.roughWeight);
      } else {
        let codes = this.order.afterCode + "";
        if (codes.length > 6) {
          this.$refs["roughWeight"].focus();
        } else {
          let tempData = this.order.afterCode;
          this.order.roughWeight = tempData;
          this.order.afterCode = "";
          this.$refs["afterCode"].focus();
          this.audioTxt(this.order.roughWeight);
        }
      }
      this.getOrderByAfterCode();
    },
    processOutWeight() {
      let me = this;
      if (me.outType != 1) {
        return;
      }
      let weight = me.outWeight + "";
      if (weight.indexOf(".") == -1) {
        if (weight.length <= 6) {
          this.$refs["outAfterCode"].focus();
          this.audioTxt(me.outWeight);
        } else {
          let tempData = me.outWeight;
          me.outAfterCode = tempData;
          me.outWeight = 0;
          this.$refs["outWeight"].focus();
        }
      } else {
        this.$refs["outAfterCode"].focus();
        this.audioTxt(me.outWeight);
      }
      this.outProcess();
    },
    processOutAfterCode() {
      let me = this;
      if (me.outType == 1) {
        if (me.outAfterCode.indexOf(".") > -1) {
          let tempData = me.outAfterCode;
          me.outWeight = tempData;
          me.outAfterCode = "";
          me.$refs["outAfterCode"].focus();
          me.audioTxt(me.outWeight);
        } else {
          let codes = me.outAfterCode + "";
          if (codes.length > 6) {
            me.$refs["outWeight"].focus();
          } else {
            let tempData = me.outAfterCode;
            me.outWeight = tempData;
            me.outAfterCode = "";
            me.$refs["outAfterCode"].focus();
            me.audioTxt(me.outWeight);
          }
        }
      }
      me.outProcess();
    },
    outProcess() {
      let me = this;
      if (!me.outAfterCode) {
        // me.$message.warning("请扫描单号");
        return;
      }
      if (me.outType == 1) {
        if (!me.outWeight || me.outWeight <= 0) {
          // me.$message.warning("请先复称重");
          me.$refs["outWeight"].focus();
          return;
        }
      }
      me.$http.ajax({
        url: "order/getOrderByAfterCode/" + me.outAfterCode,
        code: "htk",
        success: res => {
          me.outOrder = res;
          if (me.outOrder) {
            if (!me.outType || me.outType != 1) {
              me.outWeight = me.outOrder.roughWeight;
            } else {
              me.audioTxt(me.outWeight);
            }
            let findItem = me.outTableData.find(item => {
              return item.afterCode == me.outAfterCode;
            });
            if (findItem) {
              me.$set(findItem, "roughWeight", me.outWeight);
            } else {
              if (me.outTableData.length > 150) {
                me.outTableData = [];
              }
              me.outTableData.unshift({
                prdCode: me.outOrder.prdCode,
                consumerCode: me.outOrder.consumerCode,
                consumerName: me.consumerName,
                destination: me.outOrder.destination,
                afterCode: me.outOrder.afterCode,
                roughWeight: me.outWeight,
                weight: !me.outOrder.weight ? 0 : me.outOrder.weight,
                transportationName: me.outOrder.transportationName,
                netWeight: (
                  parseFloat(me.outWeight) - parseFloat(me.outOrder.weight)
                ).toFixed(3)
              });
            }
            me.updateOrderOut();
          } else {
            me.$message.warning("没有查询到该单号或者订单未入库");
            me.audioTxt("未入库");
            me.outAfterCode = "";
            me.$refs["outAfterCode"].focus();
          }
        }
      });
    },
    updateOrderOut() {
      let me = this;
      me.$http.ajax({
        url: "order/updateOrderOut",
        data: {
          ids: [me.outOrder.id],
          outWeight: me.outWeight,
          state: 25
        },
        code: "htk",
        success: res => {
          me.$message.success("订单状态已改为[已出库]");
          me.outAfterCode = "";
          me.outWeight = 0;
          me.$refs.outAfterCode.focus();
        }
      });
    },
    rollback(row) {
      let me = this;
      me.$http.ajax({
        url: "order/updateOrderStateByAfterCode/" + row.afterCode + "/10",
        code: "htk",
        success: res => {
          me.$message.success("已回撤为[预报]状态");
          me.$refs.roughWeight.focus();
          let findItemIndex = me.tableData.findIndex(item => {
            return item.afterCode == row.afterCode;
          });
          if (findItemIndex > -1) {
            me.tableData.splice(findItemIndex, 1);
          }
        }
      });
    },
    getOrderByAfterCode() {
      let me = this;
      if (!me.order.afterCode) {
        return;
      }
      me.$http.ajax({
        url: "order/getOrderByAfterCode/" + me.order.afterCode,
        code: "htk",
        success: res => {
          me.oldOrder = res;
          if (me.oldOrder.afterCode) {
            me.newOrder = Object.assign({}, me.oldOrder);
          }
          if (
            me.order.roughWeight > 0 &&
            me.order.afterCode &&
            me.order.afterCode.length > 0
          ) {
            me.submitOrder();
          }
        }
      });
    },
    submitOrder() {
      let me = this;
      if (!me.order.prdCode) {
        me.$message.warning("请选择左侧列表的产品（点击一行即选择）");
        return;
      }
      if (!me.order.consumerCode) {
        me.$message.warning("请选择客户编码");
        return;
      }
      if (!me.order.destination) {
        me.$message.warning("请选择目的地");
        return;
      }
      if (!me.order.afterCode) {
        me.$message.warning("请扫描转运单号条码");
        return;
      }
      if (!me.order.roughWeight || me.order.roughWeight <= 0) {
        me.$message.warning("请先称重");
        return;
      }
      if (!me.oldOrder.afterCode) {
        me.order.weight = me.order.roughWeight;
      }
      if (me.newOrder.afterCode) {
        me.newOrder.roughWeight = me.order.roughWeight;
        me.newOrder.longs = me.order.longs;
        me.newOrder.height = me.order.height;
        me.newOrder.width = me.order.width;
        me.order = Object.assign({}, me.newOrder);
      }
      me.order.state = 15;
      me.$http.ajax({
        url: "order/saveOrder",
        data: me.order,
        code: "htk",
        success: res => {
          me.$message.success("保存成功");
          let findItem = me.tableData.find(item => {
            return item.afterCode == me.order.afterCode;
          });
          if (findItem) {
            me.$set(findItem, "roughWeight", me.order.roughWeight);
          } else {
            me.tableData.unshift({
              orderId: me.order.id,
              prdCode: me.order.prdCode,
              consumerCode: me.order.consumerCode,
              consumerName: me.consumerName,
              destination: me.order.destination,
              afterCode: me.order.afterCode,
              roughWeight: me.order.roughWeight,
              weight: me.order.weight,
              transportationName: me.transportationName,
              destinationName: me.destinationName,
              netWeight: (
                parseFloat(me.order.roughWeight) - parseFloat(me.order.weight)
              ).toFixed(3)
            });
          }
          me.order.id = "";
          me.order.afterCode = "";
          me.order.roughWeight = 0;
          me.order.weight = 0;
          me.newOrder = {};
          me.oldOrder = {};
        }
      });
    },
    handleCurrentChange(row) {
      console.log(row);
      this.order.prdCode = row.prdCode;
      this.order.prdName = row.prdName;
      this.order.destination = "";
      this.order.transportation = "";
      this.order.consumerCode = "";
      this.tableData = [];
      this.getPriceList();
    },
    getPrdList() {
      let me = this;
      me.$http.ajax({
        url: "product/getAll",
        code: "htk",
        success: res => {
          me.prds = res;
        }
      });
    },
    getPriceList() {
      let me = this;
      if (!me.order.prdCode) {
        return;
      }
      me.$http.ajax({
        url: "price/getDestination",
        code: "htk",
        data: {
          prdCode: me.order.prdCode,
          countryCode: me.order.destination
        },
        success: res => {
          me.prices = res;
        }
      });
    },
    getParentConsumers() {
      let me = this;
      me.$http.ajax({
        url: "consumer/listChildren/" + me.$store.state.admin.orgId,
        success: res => {
          me.parentConsumers = res;
          me.consumerOptions = res;
        }
      });
    },
    filterMethod(query) {
      let me = this;
      if (!query.trim()) {
        me.consumerOptions = me.parentConsumers;
      } else {
        me.consumerOptions = me.parentConsumers.filter(consumer => {
          return (
            consumer.name.toLowerCase().indexOf(query.toLowerCase()) > -1 ||
            consumer.code.toLowerCase().indexOf(query.toLowerCase()) > -1
          );
        });
      }
    }
  }
};
</script>

<style>
.el-popper {
  min-width: 210px;
}
.prd-table .el-table__body tr.current-row > td {
  background-color: #00aaff;
  color: #fff;
}
.titlea {
  padding: 10px;
  background: #f0f0f0;
}
.scanweight .el-tabs__content {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.scanweight .el-tab-pane {
  flex: 1;
  display: flex;
  flex-direction: column;
}
</style>
